package com.face.operate.jsu;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.face.common.jsu.DeletePhoto;
import com.megvii.cloud.http.CommonOperate;
import com.megvii.cloud.http.FaceSetOperate;

public class Face_Operate {
	public static String          confidence = null;
	public static CommonOperate   com  = null;
	public static FaceSetOperate  fst  = null;
	public static LostToken_Operate  tok  = null;
	public static String getConfidence() {
		return confidence;
	}
	public static void setConfidence(String confidence) {
		Face_Operate.confidence = confidence;
	}
	public Face_Operate(){
		com = new CommonOperate(API.APIkey, API.APIsecret,false);
		fst = new FaceSetOperate(API.APIkey, API.APIsecret,false);
		tok = new LostToken_Operate();
	}
	/*
	 * 处理接收到的图片
	 * 判断合法性，若图片不合法则删除图片
	 * 同时返回facetoken
	 */
	public static String handleThePhoto(String filepath) throws IOException{
		
		byte[] fb = Face_Operate.toByteArray(filepath);
		String facetoken = Face_Operate.toFaceToken(fb);
		try {
			if (facetoken.equals("failed")) {
				DeletePhoto.deletePhoto(filepath);
			} 
	}catch (Exception e) {
		
	}
		return facetoken;
	}
	/*
	 * 获取facesets
	 */
	public static String get_faceSets(String tags){
		String result = null;
		try {
			result = new String(fst.getFaceSets(tags).getContent());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/*
	 * 创建faceset
	 */
	public static void create_faceset(String faceset_outid){
		try {
			fst.createFaceSet(API.faceset_dispalyName, faceset_outid, API.faceset_tags, null, API.facset_userdata, API.faceset_ForceMerge);
			System.out.println("创建成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * 将图片文件转换成byte数组
	 */
	public static byte[] toByteArray(String filename) throws IOException{
		  
        File f = new File(filename);  
        if (!f.exists()) {  
            throw new FileNotFoundException(filename);  
        }  
  
        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());  
        BufferedInputStream in = null;  
        try {  
            in = new BufferedInputStream(new FileInputStream(f));  
            int buf_size = 1024;  
            byte[] buffer = new byte[buf_size];  
            int len = 0;  
            while (-1 != (len = in.read(buffer, 0, buf_size))) {  
                bos.write(buffer, 0, len);  
            }  
            System.out.println("转换成功");
            return bos.toByteArray();  
            
        } catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        } finally {  
            try {  
                in.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            bos.close();  
        } 
	}
	/*
	 * 提取faceToken
	 */
	public static String toFaceToken(byte[] f){
		String get_Token = "";
		String tag       = "initail";
		System.out.println("开始提取");
		try {
			//com.detectByte(f, 1, null)调用者提供图片文件，进行人脸检测。
			tag = new String(com.detectByte(f, 1, null).getContent());
			System.out.println("tag:"+tag);
			if(!(tag.contains("face_token"))){
				get_Token = "failed";
			}else{
				get_Token = tag.substring(tag.indexOf("face_token")+14,tag.indexOf("face_token")+46);
			}
			
			System.out.println("提取成功"+get_Token);
		} catch (Exception e) {
			System.out.println("提取失败");
			e.printStackTrace();
			
		}
		return get_Token;
	}
	/*
	 * 增加faceToken至faceset中
	 */
	public static void add_faceset(String facetoken,String faceset_outid){
		try {
			fst.addFaceByOuterId(facetoken, faceset_outid);
			System.out.println("增加成功");
		} catch (Exception e) {
			System.out.println("增加失败");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/*
	 * 将一个或多个facetoken从某faceset中移除
	 * 多个facetoken使用逗号分隔
	 */
	public static void removeFace(String outerId, String faceTokens){
		try {
			fst.removeFaceFromFaceSetByOuterId(outerId, faceTokens);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * 展示faceSet信息
	 */
	public static void show_faceset(String faceset_outid){
		try {
			System.out.println(new String(fst.getDetailByOuterId(faceset_outid).getContent()));
			System.out.println("展示成功");
		} catch (Exception e) {
			System.out.println("展示失败");
			e.printStackTrace();
		}
		
	}
	/*
	 * 删除faceset
	 */
	public static void delete_faceset(String faceset_outid){
		try{
			fst.deleteFaceSetByOuterId(faceset_outid, 0);
			System.out.println("删除成功");
		}catch (Exception e) {
			System.out.println("删除失败");
		}
	}
	/*
	 * 搜索faceset并且给出最相似的两个facetoken封装成List返回
	 */
	public static List<String> search_faceset(byte[] f,String face_token,String faceset_outid){	
		List<String> faceList = new ArrayList<String>();
		try {
			//com.searchByOuterId在Faceset中找出与目标人脸最相似的一张或多张人脸
		    String result = new String(com.searchByOuterId(face_token, null, f, faceset_outid, 5).getContent());
			System.out.println("serch返回的结果："+result);
//			int start = result.indexOf("confidence"); 
//			face_Operate.setConfidence(result.substring(start,start+18));
		    Pattern p = Pattern.compile("\"face_token\": \".*?\"");
			Matcher m = p.matcher(result);
			while(m.find()){
				String results = m.group();
				String newresults = results.substring(results.indexOf(":")+3, results.length()-1);
				faceList.add(newresults);
			}
		    System.out.println("搜索成功");
			
		} catch (Exception e) {
			System.out.println("搜索失败");
			e.printStackTrace();
		}
		
		return faceList;
	}
	//将指定路径下的所有图片提取信息并加入到faceset中
//	public static void ListAllPhoto () {
//		List<String> faceList = new ArrayList<String>();
//		faceList  = tok.Faceadd("E:\\newphoto");
//		for(int i = 0 ; i < faceList.size(); i++){
//	    try {
//			byte[] f = toByteArray(faceList.get(i));
//			String face_token = toFaceToken(f);
//			System.out.println(face_token);
//			tok.Save(face_token, faceList.get(i));
//			add_faceset(face_token);
//		  } catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		 }
//		}
//    }
//	public  void  initialize(){
//		delete_faceset();
//		create_faceset();
//	}
//      public static void main(String[] args) {
//		face_Operate face =new face_Operate();
//		face.ListAllPhoto();
//      }
}
